package com.sghj.utils.Validate.username;


import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义用户名校验注解实现
 *
 * @author ruoyi
 */
public class UserNameValidator implements ConstraintValidator<UserName, String>
{
    private static final String USERNAME_PATTERN = "^[a-zA-Z][a-zA-Z0-9]{5,15}$";

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext)
    {
        if (value==null){
            return true;
        }

        if (StringUtils.isBlank(value))
        {
            return false;
        }
        return isUserName(value);
    }

    public static boolean isUserName(String value)
    {
        Pattern pattern = Pattern.compile(USERNAME_PATTERN);
        Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }
}